package com.example.administrator.hqq.fragment.discover;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.View.popup_window.CommonPopupWindow;
import com.example.administrator.hqq.activity.drag.PhotoActivity;
import com.example.administrator.hqq.activity.group.JoinGroupActivity;
import com.example.administrator.hqq.activity.post.PostDetailsActivity;
import com.example.administrator.hqq.activity.post.ReleasePostActivity;
import com.example.administrator.hqq.adapter.discover.PostListAdapter;
import com.example.administrator.hqq.base.MyFragemnt;
import com.example.administrator.hqq.bean.ForumComment;
import com.example.administrator.hqq.bean.post.PostModuleBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.message.PostDetailsMessageEvent;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * 贴子列表页
 */
public class PostModuleFragment extends MyFragemnt implements View.OnClickListener {


    private final String TAG = this.getClass().getSimpleName();
    Unbinder unbinder;
    @BindView(R.id.group_list_et)
    TextView groupListEt;
    @BindView(R.id.create_post)
    ImageView createPost;
    @BindView(R.id.forum_list_screen)
    ImageView forumListScreen;
    @BindView(R.id.group_search_button)
    ImageView groupSearchButton;
    @BindView(R.id.group_search)
    AutoRelativeLayout groupSearch;
    @BindView(R.id.navigation_bar)
    AutoRelativeLayout navigationBar;
    @BindView(R.id.group_lv)
    ListView groupLv;
    @BindView(R.id.empty)
    EmptyLayout empty;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.base_auto)
    AutoLinearLayout baseAuto;
    @BindView(R.id.transparency_background)
    View transparencyBackground;
    private View inflate;
    private String amount = "20";
    private Boolean isRefresh = false;
    private List<PostModuleBean.DataBean> listViewData;//数据源
    private ArrayAdapter<String> adapter;
    private int mTouchSlop;//系统认为的最小滑动距离
    private float mFirstY;//用户首次触摸的Y坐标
    private float mLastY;//用户滑动结束时Y坐标
    private ObjectAnimator mAnimator;//将控件与动画联系起来的类（可以使指定的控件，实现指定的动画效果）
    private boolean mShow = true;//toolbar是否显示
    private PostListAdapter postListAdapter;
    private int page = 1;
    private int position = 0;
    private ArrayList<String> strings;
    private AlertDialog showReportAlertView;
    private String last_id = "";
    private String gender_prefer = "0";
    private String city_prefer = "0";
    private String age_prefer = "0";
    private String topic_id = "";
    private String topicName;
    private RadioButton man;
    private RadioButton woman;
    private RadioButton manUnlimited;
    private RadioButton age;
    private RadioButton ageUnlimited;
    private TextView confirmBotton;
    private CommonPopupWindow window;

    public PostModuleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        inflate = inflater.inflate(R.layout.fragment_post_module, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        EventBus.getDefault().register(this);
        initview();
//        initdata();
        return inflate;
    }

    private void initdata() {
        if (page == 1 || listViewData.size() <= 0) {
            last_id = "";
        } else {
            last_id = listViewData.get(listViewData.size() - 1).getId();
        }
        OkHttpUtils.get().url(UrlFactory.getForumList()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.topic_id, topic_id)
                .addParams(LoongsConfig.gender_prefer, gender_prefer)
                .addParams(LoongsConfig.age_prefer, age_prefer)
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .addParams(LoongsConfig.key_word, "")
                .addParams(LoongsConfig.last_id, last_id)
                .addParams(LoongsConfig.city_prefer, city_prefer)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                if (baseAuto != null)
                    if (refreshLayout != null) {
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
                Gson gson = new Gson();
                PostModuleBean postModuleBean = gson.fromJson(response, PostModuleBean.class);
                if (postModuleBean.getCode() == 200) {
                    empty.hide();
                    if (page == 1) {
                        if (postModuleBean.getData() == null || postModuleBean.getData().size() == 0) {
                            empty.showEmpty();
                        }
                        listViewData.clear();
                    }
                    listViewData.addAll(postModuleBean.getData());
                    postListAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initview() {
        gender_prefer = LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.forum_gender_screen, "0");
        age_prefer = LoongsConfig.getUsersIdSPUtils().getString(LoongsConfig.forum_age_screen, "0");
        strings = new ArrayList<>();
        listViewData = new ArrayList<>();
        postListAdapter = new PostListAdapter(getContext(), listViewData);
        groupLv.setAdapter(postListAdapter);
        postListAdapter.setOnClick(new PostListAdapter.OnClick() {
            @Override
            public void lookPic(int i, int i1) {
                ArrayList<String> strings = new ArrayList<>();
                for (int i2 = 0; i2 < listViewData.get(i).getPicture_url().size(); i2++) {
                    strings.add(listViewData.get(i).getPicture_url().get(i2).getOrigin());
                }
                PhotoActivity.start(getContext(), strings, i1);
            }

            @Override
            public void giveLike(final int i, final ImageView image, TextView textView) {
                listViewData.get(i).setLike_amount(image.isSelected() ? listViewData.get(i).getLike_amount() - 1 : listViewData.get(i).getLike_amount() + 1);
                listViewData.get(i).setLike_state(image.isSelected() ? 0 : 1);
                postListAdapter.notifyDataSetChanged();
                OkHttpUtils.get().url(UrlFactory.getForumlike())
                        .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                        .addParams(LoongsConfig.forum_id, listViewData.get(i).getId())
                        .addParams(LoongsConfig.value, image.isSelected() ? "0" : "1")
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "点赞onError: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "点赞onResponse: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt(LoongsConfig.code) == 200) {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }

            @Override
            public void details(int i) {
                position = i;
                Log.e("kang", "details: ");
                Intent intent = new Intent(getContext(), PostDetailsActivity.class);
                intent.putExtra(LoongsConfig.forum_id, listViewData.get(i).getId());
                intent.putExtra(LoongsConfig.name, topicName);
                intent.putExtra(LoongsConfig.topic, topic_id);
                intent.putExtra(LoongsConfig.forumPosition, i);
                startActivity(intent);
            }

            @SuppressLint("ResourceType")
            @Override
            public void report(final int i) {
                if ("MINE".equals(listViewData.get(i).getType())) {
                    AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(getContext());
                    normalDialog.setTitle("确定要删除此帖子吗");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    deleteForum(i);
                                }
                            });
                    normalDialog.setNegativeButton("关闭",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //...To-do
                                }
                            });
                    // 显示
                    normalDialog.show();
                } else {
                    reportForum(i);
                }

            }

            @Override
            public void joinGroup(int position){
                joinGroupCheck(position);
            }
        });
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                page = 1;
                initdata();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //上拉加载
                page++;
                initdata();
            }
        });
        //监听listview的滑动
//        setScroll();
    }

    /**
     * 进群检测
     * @param position
     */
    private void joinGroupCheck(final int position) {
        Log.e(TAG, "joinGroupCheck: "+position );
        OkHttpUtils.get().url(UrlFactory.getGroupCheck())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, listViewData.get(position).getGroup().getGroup_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "进群检测onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    String description = jsonObject.getString("description");
                    HintWordsUtils.showMarkeWords(code,description);
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.GROUP);
                    SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).put(LoongsConfig.Conversation.ConversationID, listViewData.get(position).getGroup().getGroup_id());
                    switch (code) {
                        case 200:
                        case 201:
                            RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.GROUP, listViewData.get(position).getGroup().getGroup_id(), "话圈圈");
                            break;
                        case 202:
                            Intent intent = new Intent(getContext(), JoinGroupActivity.class);
                            intent.putExtra(LoongsConfig.group_id, listViewData.get(position).getGroup().getGroup_id());
                            startActivity(intent);
                            break;
                        case 203:
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 举报帖子内容
     * @param i
     */
    private void reportForum(final int i) {
        strings.clear();
        for (String s : getContext().getResources().getStringArray(R.array.forum_report)) {
            strings.add(s);
        }
        showReportAlertView = AlertViewFactory.getInstance().getShowReportAlertView(getContext(), strings, new AlertViewFactory.ReportOnClickListener() {
            @Override
            public void submit(int position) {
                Log.e(TAG, "submit: " + position);
                showReportAlertView.cancel();
                OkHttpUtils.get().url(UrlFactory.ReportForum())
                        .addParams(LoongsConfig.id, listViewData.get(i).getId())
                        .addParams(LoongsConfig.type, "0")
                        .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                        .addParams(LoongsConfig.reason_id, position + 101 + "")
                        .build().execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, "举报onError: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "举报response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            int code = jsonObject.getInt(LoongsConfig.code);
                            HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                            if (code == 200) {
                                ToastUtils.showShort("已提交举报");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                listViewData.remove(i);
                postListAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 删除自己的帖子
     * @param i
     */
    private void deleteForum(final int i) {
        OkHttpUtils.get().url(UrlFactory.deleterMyforum()).tag(this)
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.forum_id, listViewData.get(i).getId())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "贴子删除onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "贴子删除onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    String description = jsonObject.getString(LoongsConfig.description);
                    if (code == 200) {
                        listViewData.remove(i);
                        postListAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.create_post, R.id.forum_list_screen})
    public void onViewClicked(final View view) {
        switch (view.getId()) {
            case R.id.create_post:
                Intent intent = new Intent(getContext(), ReleasePostActivity.class);
                intent.putExtra(LoongsConfig.topic_id, topic_id);
                startActivity(intent);
                break;
            case R.id.forum_list_screen:
                    showPopupWindow();
                break;
        }
    }

    /**
     * 帖子筛选项
     */
    private void showPopupWindow() {
        window = new CommonPopupWindow(getContext(), R.layout.forum_list_screen_item, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initView() {
                View contentView = getContentView();
                View view1 = contentView.findViewById(R.id.view1);
                View view2 = contentView.findViewById(R.id.view2);
                View view3 = contentView.findViewById(R.id.view3);
                view1.setVisibility(View.GONE);
                view2.setVisibility(View.GONE);
                view3.setVisibility(View.GONE);
                man = contentView.findViewById(R.id.man);
                woman = contentView.findViewById(R.id.woman);
                manUnlimited = contentView.findViewById(R.id.man_unlimited);
                age = contentView.findViewById(R.id.age);
                ageUnlimited = contentView.findViewById(R.id.age_unlimited);
                confirmBotton = contentView.findViewById(R.id.screen_confirm_bt);
                if ("0".equals(gender_prefer))
                {
                    setPitchUpTextColor(manUnlimited);
                }else if ("1".equals(gender_prefer)){
                    setPitchUpTextColor(man);
                }else{
                    setPitchUpTextColor(woman);
                }
                if ("0".equals(age_prefer))
                {
                    setPitchUpTextColor(ageUnlimited);
                }else{
                    setPitchUpTextColor(age);
                }
            }

            @Override
            protected void initEvent() {
                man.setOnClickListener(PostModuleFragment.this);
                woman.setOnClickListener(PostModuleFragment.this);
                manUnlimited.setOnClickListener(PostModuleFragment.this);
                age.setOnClickListener(PostModuleFragment.this);
                ageUnlimited.setOnClickListener(PostModuleFragment.this);
                confirmBotton.setOnClickListener(PostModuleFragment.this);
            }

            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance = getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        transparencyBackground.setVisibility(View.GONE);
                    }
                });
            }
        };
        CommonPopupWindow.LayoutGravity layoutGravity = new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.ALIGN_LEFT | CommonPopupWindow.LayoutGravity.TO_BOTTOM);
        window.showBashOfAnchor(navigationBar, layoutGravity, 0, 0);
        transparencyBackground.setVisibility(View.VISIBLE);
    }

    public void setGender_prefer(String gender_prefer) {
        this.gender_prefer = gender_prefer;
    }

    public void setCity_prefer(String city_prefer) {
        this.city_prefer = city_prefer;
    }

    public void setAge_prefer(String age_prefer) {
        this.age_prefer = age_prefer;
    }

    public void setTopic_id(String topic_id) {
        this.topic_id = topic_id;
    }

    public void startInitData() {
        mShow = true;
        listViewData.clear();
        postListAdapter.notifyDataSetChanged();
        page = 1;
        initdata();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(PostDetailsMessageEvent messageEvent) {
        if ("2".equals(messageEvent.getType())) {
            int reply_amount = listViewData.get(messageEvent.getForumPosition()).getReply_amount();
            reply_amount++;
            listViewData.get(messageEvent.getForumPosition()).setReply_amount(reply_amount);
            postListAdapter.notifyDataSetChanged();
        } else {
            initdata();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(ForumComment forumComment) {
        switch (forumComment.getType()) {
            case CREATE_FORUM:
                page = 1;
                initdata();
                break;
            case FORUM_REPORT:
                for (PostModuleBean.DataBean listViewDatum : listViewData) {
                    if (listViewDatum.getId().equals(forumComment.getId())) {
                        listViewData.remove(listViewDatum);
                        postListAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                break;
            case DELETE_FORUM:
                for (PostModuleBean.DataBean listViewDatum : listViewData) {
                    if (listViewDatum.getId().equals(forumComment.getId())) {
                        listViewData.remove(listViewDatum);
                        postListAdapter.notifyDataSetChanged();
                        break;
                    }
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void setTopicName(String topicName) {
        this.topicName = topicName;
        this.groupListEt.setText(topicName);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.man:
                gender_prefer = "1";
                setPitchUpTextColor(man);
                break;
            case R.id.woman:
                gender_prefer = "2";
                setPitchUpTextColor(woman);
                break;
            case R.id.man_unlimited:
                gender_prefer = "0";
                setPitchUpTextColor(manUnlimited);
                break;
            case R.id.age:
                age_prefer = "1";
                setPitchUpTextColor(age);
                break;
            case R.id.age_unlimited:
                age_prefer = "0";
                setPitchUpTextColor(ageUnlimited);
                break;
            case R.id.screen_confirm_bt:
                LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.forum_gender_screen,gender_prefer);
                LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.forum_age_screen, age_prefer);
                window.dismiss();
                page=1;
                initdata();
                break;
        }
    }

    public void setPitchUpTextColor(RadioButton rad) {
        switch (rad.getId()) {
//            case R.id.locality:
//            case R.id.locality_unlimited:
//                locality.setTextColor(Color.parseColor("#8D8D8D"));
//                localityUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
//                break;
            case R.id.man:
            case R.id.woman:
            case R.id.man_unlimited:
                man.setTextColor(Color.parseColor("#8D8D8D"));
                woman.setTextColor(Color.parseColor("#8D8D8D"));
                manUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
                break;
            case R.id.age:
            case R.id.age_unlimited:
                age.setTextColor(Color.parseColor("#8D8D8D"));
                ageUnlimited.setTextColor(Color.parseColor("#8D8D8D"));
                break;
        }
        rad.setTextColor(Color.parseColor("#4B8978"));
    }
}
